#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Pinterest图片搜索脚本使用示例
"""

from pinterest_image_scraper import PinterestImageScraper
import json


def search_and_save_images(query: str, output_file: str = None):
    """
    搜索图片并保存结果
    
    Args:
        query: 搜索关键词
        output_file: 输出文件路径（可选）
    """
    scraper = PinterestImageScraper()
    
    print(f"🔍 正在搜索关键词: '{query}'")
    print("-" * 50)
    
    # 搜索图片
    image_urls = scraper.search_images(query, limit=10)
    
    if image_urls:
        print(f"✅ 成功找到 {len(image_urls)} 张图片:")
        print()
        
        for i, url in enumerate(image_urls, 1):
            print(f"{i:2d}. {url}")
        
        # 如果指定了输出文件，保存结果
        if output_file:
            result = {
                "query": query,
                "total_images": len(image_urls),
                "image_urls": image_urls,
                "timestamp": str(datetime.now())
            }
            
            with open(output_file, 'w', encoding='utf-8') as f:
                json.dump(result, f, ensure_ascii=False, indent=2)
            
            print(f"\n💾 结果已保存到: {output_file}")
    else:
        print("❌ 未找到图片，请尝试其他关键词")
    
    return image_urls


def interactive_search():
    """
    交互式搜索模式
    """
    print("🎨 Pinterest图片搜索工具")
    print("=" * 50)
    
    while True:
        try:
            query = input("\n请输入搜索关键词 (输入 'quit' 退出): ").strip()
            
            if query.lower() in ['quit', 'exit', 'q']:
                print("👋 再见!")
                break
            
            if not query:
                print("⚠️  请输入有效的搜索关键词")
                continue
            
            # 询问是否保存结果
            save_choice = input("是否保存结果到文件? (y/n): ").strip().lower()
            output_file = None
            
            if save_choice in ['y', 'yes']:
                output_file = f"search_results_{query.replace(' ', '_')}.json"
            
            # 执行搜索
            search_and_save_images(query, output_file)
            
        except KeyboardInterrupt:
            print("\n\n👋 程序已退出")
            break
        except Exception as e:
            print(f"❌ 发生错误: {str(e)}")


if __name__ == "__main__":
    import sys
    from datetime import datetime
    
    if len(sys.argv) > 1:
        # 命令行模式
        query = " ".join(sys.argv[1:])
        search_and_save_images(query)
    else:
        # 交互式模式
        interactive_search()
